﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using BoYuan.MvcCodeTemplates;
using BoYuan.MvcCodeTemplates.DBMappingRules;
using BoYuan.MvcCodeTemplates.FineUIMvc.Template;
using FineUIMvc;
using SqlSugar;

namespace BoYuan.MvcCodeGenerator.Controllers
{
    public class BaseController : FineUIMvcController
    {
        public SqlSugarClient MyInstance()
        {
            var db = BoYuan.DBServices.DB_Base.Instance;
            if (Session["db"] != null)
                db.CurrentConnectionConfig.ConnectionString = GetConnectionString();
            return db;
        }

        public string GetConnectionString()
        {
            return Session["db"] != null ? Session["db"].ToString() : ConfigurationManager.AppSettings["ConnectionString"];
        }

        /// <summary>
        ///  获取表信息
        /// </summary>
        /// <param name="likeName"></param>
        /// <returns></returns>
        public List<string> GetTableInfos(string likeName = "")
        {
            var db = MyInstance();

            var tableList = db.DbMaintenance.GetTableInfoList(false)
                .OrderBy(p => p.Name)
                .Select(p => p.Name)
                .ToList();

            if (likeName.Length == 0)
            {
                return tableList;
            }
            else
            {
                return tableList
                    .Where(p => p.IndexOf(likeName, StringComparison.OrdinalIgnoreCase) >= 0)
                    .OrderBy(p => p)
                    .ToList();
            }
        }

        /// <summary>
        /// 获取字段信息集合，根据表
        /// </summary>
        /// <param name="tableName">表名称</param>
        /// <returns></returns>
        public List<DbColumnInfo> GetColumnDataByTableName(string tableName)
        {
            var db = MyInstance();
            var list = db.DbMaintenance.GetColumnInfosByTableName(tableName);

            foreach (var cm in list)
            {
                if (cm.ColumnDescription == null)
                {
                    cm.ColumnDescription = string.Empty;
                }
                if (cm.DefaultValue == null)
                {
                    cm.DefaultValue = string.Empty;
                }

                cm.PropertyName = DataTypeMapping.Mssql.GetBaseDataType()[cm.DataType];
            }
            return list;
        }

        /// <summary>
        /// 生成FineuiMvc代码到指定的位置
        /// </summary>
        /// <param name="savePath">生成代码的物理地址</param>
        /// <param name="table">表信息实体</param>
        public void CreateFineuiMvcCode(string savePath, TableModel table)
        {
            string controllersPath = savePath + "/" + table.Namespace2Str + "/Controllers";// c:/code/Areas/Admin/Controllers
            string viewsPath = savePath + "/" + table.Namespace2Str + "/Views/" + table.TableName;// c:/code/Areas/Admin/views/SysAdmin
            string sharedPath = savePath + "/" + table.Namespace2Str + "/Views/Shared";// c:/code/Areas/Admin/views/Shared
            if (!Directory.Exists(controllersPath))
            {
                Directory.CreateDirectory(controllersPath); //在根目录下建立文件夹
            }
            if (!Directory.Exists(viewsPath))
            {
                Directory.CreateDirectory(viewsPath); //在根目录下建立文件夹
            }
            if (!Directory.Exists(sharedPath))
            {
                Directory.CreateDirectory(sharedPath); //在根目录下建立文件夹
            }

            string templateInfo;

            //controllers
            templateInfo = ControllerTemplate.GetCode(table);
            System.IO.File.WriteAllText(controllersPath + "/" + table.TableName + "Controller.cs", templateInfo, Encoding.UTF8);

            //AreaRegistration.cs
            templateInfo = AreaRegistrationTemplate.GetCode(table);
            System.IO.File.WriteAllText(savePath + "/" + table.Namespace2Str + "/" + table.Namespace2Str + "AreaRegistration.cs", templateInfo, Encoding.UTF8);

            //views
            templateInfo = AddcshtmlTemplate.GetCode(table);
            System.IO.File.WriteAllText(viewsPath + "/Add.cshtml", templateInfo, Encoding.UTF8);

            templateInfo = IndexcshtmlTemplate.GetCode(table);
            System.IO.File.WriteAllText(viewsPath + "/Index.cshtml", templateInfo, Encoding.UTF8);

            //_ViewStart.cshtml
            templateInfo = ViewStartTemplate.GetCode(table);
            System.IO.File.WriteAllText(savePath + "/" + table.Namespace2Str + "/Views/_ViewStart.cshtml", templateInfo, Encoding.UTF8);

            //web.config
            templateInfo = WebConfigTemplate.GetCode(table);
            System.IO.File.WriteAllText(savePath + "/" + table.Namespace2Str + "/Views/web.config", templateInfo, Encoding.UTF8);

        }

        #region OnActionExecuting

        /// <summary>
        /// 动作方法调用之前执行
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
        }


        #endregion

        #region 实用函数


        /// <summary>
        /// 获取网址的完整路径
        /// </summary>
        /// <param name="virtualPath"></param>
        /// <returns></returns>
        public string GetAbsoluteUrl(string virtualPath)
        {
            // http://benjii.me/2015/05/get-the-absolute-uri-from-asp-net-mvc-content-or-action/
            var urlBuilder = new System.UriBuilder(Request.Url.AbsoluteUri)
            {
                Path = Url.Content(virtualPath),
                Query = null,
            };

            return urlBuilder.ToString();
        }

        #endregion


    }
}